import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from '../views/Index'
import Manager from '../views/Manager'
import Login from '../views/Login'

Vue.use(VueRouter)

const routes = [{
    path: "/",
    component: Index
}, {
    path: "/Manager",
    component: Manager
}, {
    path: "/Login",
    component: Login
}]

const router = new VueRouter({
    routes
})


// 路由守卫
router.beforeEach((to,from,next)=>{

    // 如果请求的是Login组件，则直接放行
    if (to.path == "/Login") {
        next();
        return;
    }

    // 获取前端localStorage中的token
    let token = localStorage.getItem("token");

    // 如果token为null，则让用户去登录
    if (!token) {
        // 记录用户原本想要访问的资源地址
        router.app.$store.commit("setToUrl", to)
        next("/Login");
        return;
    }

    // 如果token不为null，则向后端发起校验token的请求
    let headers = { "Content-Type": "text/plain" };
    router.app.$axios.post("http://localhost:8061/auth/verify", token, { headers }).then(response => {
        if (response.data.code != 200) {
            next("/Login");
        } else {
            next();
        }
    });
});

export default router